<template>
  <div>
    <a-table
      :columns="columns"
      :dataSource="users"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      rowKey="id"
      bordered
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'avatar'">
          <a-avatar :src="record.userAvatar" class="user-avatar">
            {{ !record.userAvatar ? record.userName?.charAt(0).toUpperCase() : '' }}
          </a-avatar>
        </template>
        <template v-if="column.key === 'isActive'">
          <a-tag :color="record.userRole === 'admin' ? 'green' : 'blue'">
            {{ record.userRole === 'admin' ? '管理员' : '用户' }}
          </a-tag>
        </template>
        <template v-if="column.key === 'actions'">
          <a-space>
            <a-tooltip title="编辑">
              <a-button
                type="primary"
                class="edit-button"
                shape="circle"
                @click="editUser(record.id)"
              >
                <template #icon><EditOutlined /></template>
              </a-button>
            </a-tooltip>
            <a-popconfirm
              title="确定要删除该用户吗？"
              @confirm="deleteUser(record.id)"
              ok-text="确定"
              cancel-text="取消"
            >
              <a-tooltip title="删除">
                <a-button type="primary" danger shape="circle">
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </a-tooltip>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 编辑用户弹窗 -->
    <a-modal
      v-model:visible="editModalVisible"
      title="编辑用户"
      @ok="handleEditOk"
      @cancel="handleEditCancel"
      :confirmLoading="confirmLoading"
      width="600px"
    >
      <a-form :model="editForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="用户名">
          <a-input v-model:value="editForm.userName" />
        </a-form-item>
        <a-form-item label="头像">
          <a-input v-model:value="editForm.userAvatar" placeholder="请输入头像URL" />
        </a-form-item>
        <a-form-item label="角色">
          <a-select v-model:value="editForm.userRole">
            <a-select-option value="user">普通用户</a-select-option>
            <a-select-option value="admin">管理员</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, type Ref } from 'vue'
import { EditOutlined, DeleteOutlined } from '@ant-design/icons-vue'
import {
  getUserByIdUsingGet,
  listUserVoByPageUsingPost,
  updateUserUsingPost,
  deleteUserUsingPost,
} from '@/api/userController'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'

const users: Ref<API.UserVO[]> = ref([])
const loading = ref(false)
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total: number) => `共 ${total} 条`,
})

const columns = [
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
  },
  {
    title: '头像',
    dataIndex: 'userAvatar',
    key: 'avatar',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    customRender: ({ text }: { text: string }) => {
      return text ? dayjs(text).format('YYYY-MM-DD') : '-'
    },
  },
  {
    title: '角色',
    dataIndex: 'userRole',
    key: 'isActive',
  },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    align: 'center',
  },
]

// 获取用户列表
const loadData = async () => {
  loading.value = true
  try {
    const res = await listUserVoByPageUsingPost({
      current: pagination.value.current,
      pageSize: pagination.value.pageSize,
    })
    if (res.data.code === 0 && res.data.data) {
      users.value = res.data.data?.records || []
      pagination.value.total = res.data.data?.total || 0
    } else {
      message.error('获取用户列表失败：' + res.data.message)
    }
  } catch (error) {
    message.error('获取用户列表失败' + error)
  } finally {
    loading.value = false
  }
}

// 处理表格变化（分页、排序等）
const handleTableChange = (pag: any) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  loadData()
}

// 编辑相关的状态
const editModalVisible = ref(false)
const confirmLoading = ref(false)
const editForm = ref<Partial<API.UserVO>>({
  id: undefined,
  userName: '',
  userAvatar: '',
  userRole: '',
})

async function editUser(userId: number) {
  loading.value = true
  try {
    const res = await getUserByIdUsingGet({
      id: userId,
    })
    if (res.data.code === 0 && res.data.data) {
      editForm.value = { ...res.data.data }
      editModalVisible.value = true
    } else {
      message.error('该用户不存在')
    }
  } catch (error) {
    message.error('获取用户失败' + error)
  } finally {
    loading.value = false
  }
}

const handleEditOk = async () => {
  confirmLoading.value = true
  try {
    // TODO: 调用更新用户的API
    const res=await updateUserUsingPost({
      ...editForm.value,
    })
    if(res.data.code===0 && res.data.data){
      message.success('更新成功')
      editModalVisible.value = false
      await loadData() // 重新加载数据
    }else{
      message.error('更新失败')
    }
 
  } catch (error) {
    message.error('更新失败'+error)
  } finally {
    confirmLoading.value = false
  }
}

const handleEditCancel = () => {
  editModalVisible.value = false
  editForm.value = {
    id: undefined,
    userName: '',
    userAvatar: '',
    userRole: '',
  }
}

async function deleteUser(userId: number) {
  try {
    const res = await deleteUserUsingPost({ id: userId })
    if (res.data.code === 0) {
      message.success('删除成功')
      await loadData() // 重新加载数据
    } else {
      message.error('删除失败：' + res.data.message)
    }
  } catch (error) {
    message.error('删除失败：' + error)
  }
}

// 组件加载时获取数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.edit-button {
  background: #4f46e5;
  border-color: #4f46e5;
}

.edit-button:hover {
  background: #06b6d4 !important;
  border-color: #06b6d4 !important;
}

:deep(.ant-btn) {
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

:deep(.ant-btn:hover) {
  transform: scale(1.1);
}

.user-avatar {
  background-color: #4f46e5;
  color: #ffffff;
  font-weight: 500;
}

:deep(.ant-modal-content) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.ant-modal-header) {
  background: #4f46e5;
  padding: 16px 24px;
}

:deep(.ant-modal-title) {
  color: white;
  font-size: 18px;
  font-weight: 500;
}

:deep(.ant-modal-close-x) {
  color: white;
}

:deep(.ant-form-item-label > label) {
  color: #1e293b;
  font-weight: 500;
}

:deep(.ant-input),
:deep(.ant-select-selector) {
  border-radius: 6px !important;
}

:deep(.ant-input:hover),
:deep(.ant-select-selector:hover) {
  border-color: #4f46e5 !important;
}

:deep(.ant-input:focus),
:deep(.ant-select-selector:focus) {
  border-color: #4f46e5 !important;
  box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.2) !important;
}
</style>
